
//
//  UpdateBankPwdViewController.swift
//  d11
//
//  Created by rhonin on 2019/2/11.
//  Copyright © 2019年 Tech_001. All rights reserved.
//

import UIKit
import SwiftyJSON
class UpdateBankPwdViewController: BXBaseVC,UITableViewDelegate,UITableViewDataSource {

    let  reuseIdentifierID : NSString = "UpdatePwdItemCell"
    let  reuseIdentifierID2 : NSString = "UpdatePwdBtnCell"
    var requestType: String?
    var oldPwd : String?
    var newPwd : String?
    var confirmPwd : String?
    var isOldPwdShow : Bool?
    var  isNewPwdShow : Bool?
    var  isConfirmPwdShow : Bool?
    var vercode = ""
    
    lazy var tableView:UITableView = {
        let table = UITableView(frame:CGRect(x: 0, y: 10, width: self.view.width, height:kScreenHeight-kTabBarBottom-10), style:UITableView.Style.plain)
        table.dataSource = self
        table.delegate = self
        //table.layoutMargins = UIEdgeInsets.zero
        table.separatorStyle = .none
        table.backgroundColor  = UIColor.white
        table.showsVerticalScrollIndicator = false
        table.tableFooterView = UIView.init()
        table.separatorStyle = .none
        table.autoresizingMask = [.flexibleWidth,.flexibleHeight]
        table.estimatedRowHeight = 0
        table.estimatedSectionHeaderHeight = 0
        table.estimatedSectionFooterHeight = 0
        if #available(iOS 11.0, *) {
            table.contentInsetAdjustmentBehavior = .never
            
        } else {
            self.automaticallyAdjustsScrollViewInsets = false
        }
        return table
    }()
    
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = requestType
        self.view.backgroundColor = UIColor.white
        self.view.addSubview(self.tableView)
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return  3
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 1 {
            return 85
        }
        
        return 61
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return UIView.init()
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if  indexPath.section == 1 {
            var cell :UpdatePwdBtnCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID2 as String) as? UpdatePwdBtnCell
            if cell == nil {
                cell =  UpdatePwdBtnCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID2 as String)
            }
            cell?.callUpdateBlock {
                self.checkField()
            }
            return cell!
        }else{
            var cell :UpdatePwdItemCell? = tableView.dequeueReusableCell(withIdentifier: reuseIdentifierID as String) as? UpdatePwdItemCell
            if cell == nil {
                cell =  UpdatePwdItemCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: reuseIdentifierID as String)
            }
            
            cell?.callChangeBlock({ (text,row) in
                if row == 0{
                    self.oldPwd = text
                }else if row == 1{
                    self.newPwd = text
                }else if row == 2{
                    self.confirmPwd = text
                }else{
                    self.vercode = text
                }
            })
            cell?.callShowPwdBlock({ (row) in
                if row == 0{
                    self.isOldPwdShow =  !(self.isOldPwdShow ?? false)
                }else if row == 1{
                    self.isNewPwdShow =  !(self.isNewPwdShow ?? false)
                }else if row == 2{
                    self.isConfirmPwdShow =  !(self.isConfirmPwdShow ?? false)
                }
                self.tableView.reloadData()
            })
            var placeholder = ""
            var pwd = ""
            var iconName = ""
            var isShow = false
            
            if indexPath.row == 0{
                placeholder = "请输入旧密码"
                pwd = self.oldPwd ?? ""
                iconName = "icon_update_pwd"
                isShow = self.isOldPwdShow ?? false
            }else if indexPath.row == 1{
                placeholder = "请输入新密码(6-16位数字及字母组合)"
                pwd = self.newPwd ?? ""
                iconName = "passkeyBank"
                isShow = self.isNewPwdShow ?? false
            }else if indexPath.row == 2{
                placeholder = "请确认新密码"
                pwd = self.confirmPwd ?? ""
                iconName = "icon_update_pwd_confirm"
                isShow = self.isConfirmPwdShow ?? false
                
            }
            cell?.setData(placeholder: placeholder, pwd: pwd, iconName: iconName, isShow: isShow, row: indexPath.row)
            return cell!
        }
        
    }
    
    //校验字段
    func  checkField() -> Void {
        let predicateStr :String = "^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+){6,16}"
        if self.oldPwd == nil {
            UIHelper.alertSimpleMessage(about: "请输入旧密码!", withDescription: "", in: self)
            return
        }
        
        if self.newPwd == nil {
            UIHelper.alertSimpleMessage(about: "您输入的新密码有误（密码长度为6-16个字符,须含有字母和数字组合），请重新输入!", withDescription: "", in: self)
            return
        }else{
            let predicate =  NSPredicate(format: "SELF MATCHES %@" ,predicateStr)
            if predicate.evaluate(with: self.newPwd) == false{
                UIHelper.alertSimpleMessage(about: "您输入的新密码有误（密码长度为6-16个字符,须含有字母和数字组合），请重新输入!", withDescription: "", in: self)
                return
            }
        }
        
        if self.confirmPwd == nil {
            UIHelper.alertSimpleMessage(about: "您输入的确认密码有误（密码长度为6-16个字符,须含有字母和数字组合），请重新输入!!", withDescription: "", in: self)
            return
        }
        
        if self.newPwd != self.confirmPwd{
            UIHelper.alertSimpleMessage(about: "您两次密码输入不一致（密码长度为6-16个字符,须含有字母和数字组合），请重新输入。", withDescription: "", in: self)
            return
        }
       
        self.updatePwd()
    }
    
    func addRSA()  {
        weak var this = self
        //        RequestHelper.get(atPath: "/clientsAPIs/getPwdEncryptKey", withCompletion: { data in
        //            let dataArray = try JSONSerialization.jsonObject(with: data, options: []) as! [String: String]
        //
        let modulus = UserDefaults.standard.string(forKey: DefaultKey.MODULUS)
        let EXPONENT =  UserDefaults.standard.string(forKey: DefaultKey.EXPONENT)
        let stringAll =  this!.oldPwd!+" " + this!.newPwd!+" " + this!.confirmPwd!
        let oldPass = RSAHelper.encrypt(stringAll, modulus: modulus, exponent: EXPONENT)
        
        RequestHelper.makeGameDomainCookie()
        
        let params = ["pwd": oldPass,"verifycode":this!.vercode,"secretkey":""]
        RequestHelper.post(atPath: "/clientsAPIs/ChangePwd", withData: params as! Dictionary<String, String>, withCompletion: { (data) in
            DispatchQueue.main.async {
                this?.dismissLoadHUD()
                let json = JSON(data)
                print("修改返回\(json)")
                if json["success"].boolValue{
                    UIHelper.alertSimpleMessage(about: "修改密码成功", withDescription: "", in: self)
                    this?.perform(#selector(this?.popcont), with: nil, afterDelay: 0.5)
                }else{
                    if  json["code"].intValue == 998 || json["code"].intValue == 991{
                        UIHelper.alertSimpleMessage(about:"验证码有误，请重新输入！", withDescription: "修改登录密码失败!", in: self)
                    }else{
                        UIHelper.alertSimpleMessage(about: "修改登录密码失败", withDescription: CodeMessageHelper.get(String(json["code"].intValue)), in: self)
                    }
                    
                    let indexpath = NSIndexPath(row: 3, section: 0)
                    let cell:UpdatePwdItemCell = self.tableView.cellForRow(at: indexpath as IndexPath) as! UpdatePwdItemCell
                    cell.updateVerificationCode()
                }
            }
        }) { (error) in
            print(error)
            DispatchQueue.main.async {
                self.dismissLoadHUD()
                UIHelper.alertSimpleMessage(about: "服务器异常", withDescription: "修改登录密码失败!\(getErrorString())", in: self)
            }
        }
        //       },withError:{(error) in
        //            print(error)
        //        })
    }
    @objc func popcont()  {
        self.navigationController?.popViewController(animated: true)
    }
    
    func updatePwd() -> Void {
        // let requestPath
        self.view.endEditing(true)
        if self.requestType == UpdatePwdType.login { //修改登录密码
            self.showLoadHUD(title: "正在保存...")
            self.addRSA()
        }else if self.requestType == UpdatePwdType.withdraw{ //修改取款密码
            self.showLoadHUD(title: "正在保存...")
            weak var this  = self
            let params =  ["oldPwd":self.oldPwd ?? "","newPwd": self.newPwd ?? ""]
            RequestHelper.post(atPath: "/clientsAPIs/changeWdPwd", withData: params, withCompletion: { (data) in
                DispatchQueue.main.async {
                    this?.dismissLoadHUD()
                let json = JSON(data)
                if json["success"].boolValue{
                    UIHelper.alertSimpleMessage(about: "修改取款密码成功", withDescription: "", in: self)
                    this?.perform(#selector(this?.popcont), with: nil, afterDelay: 0.5)
                }else{
                    UIHelper.alertSimpleMessage(about: "修改取款密码失败", withDescription:  json["msg"].stringValue, in: self)
                   
                }
                }
            }) { (error) in
                print(error)
                DispatchQueue.main.async {
                    self.dismissLoadHUD()
                    UIHelper.alertSimpleMessage(about: "", withDescription: "修改取款密码失败!\(getErrorString())", in: self)
                }
            }
        }
    }
}
